package com.jiangjiang.eshop.common.json;

import com.alibaba.fastjson.JSONObject;

import java.util.Objects;

/**
 * @Author Jianghaowen
 * @Date 2021/9/23
 * @Description: 用于组合的表达式
 * @Version V1.0
 **/
public class CompositeJsonExpression implements JsonExpression{

    /**
     * json节点名称
     */
    private String jsonNodeName;

    /**
     * 子表达式
     */
    private JsonExpression childJsonExpression;

    public CompositeJsonExpression setChildJsonExpression(JsonExpression childJsonExpression) {
        this.childJsonExpression = childJsonExpression;
        return this;
    }

    public CompositeJsonExpression(String jsonNodeName) {
        this.jsonNodeName = jsonNodeName;
    }

    @Override
    public Object interpret(JsonExpressionContext context) {
        JSONObject currentJsonNode = context.getCurrentJsonNode();
        if(Objects.isNull(currentJsonNode)){
            currentJsonNode = context.getTargetJson().getJSONObject(jsonNodeName);
            context.setCurrentJsonNode(currentJsonNode);
        }else {
            currentJsonNode = currentJsonNode.getJSONObject(jsonNodeName);
            context.setCurrentJsonNode(currentJsonNode);
        }

        return childJsonExpression.interpret(context);
    }
}
